/*
 * File Name:               UITouch.cs
 * 
 * Description:             触摸类组件
 *                          坐标系定义为 左下角为(0,0) 右上角为(1,1)
 * Author:                  lisiyu <576603306@qq.com>
 * Create Date:             2017/02/28
 */

using System;
using UnityEngine;
using UnityEngine.EventSystems;

public class UITouch : UIBehaviour, IDragHandler, IPointerDownHandler
{
    private Action<Vector2> OnTouch;

    private RectTransform mRectTransform;
    private Vector3[] mScreenRect = new Vector3[4];

    protected override void Start()
    {
        base.Start();

        mRectTransform = GetComponent<RectTransform>();
        mRectTransform.GetWorldCorners(mScreenRect);
        mScreenRect[0] = UIManager.Singleton.WorldToScreenPoint(mScreenRect[0]);
        mScreenRect[1] = UIManager.Singleton.WorldToScreenPoint(mScreenRect[1]);
        mScreenRect[2] = UIManager.Singleton.WorldToScreenPoint(mScreenRect[2]);
        mScreenRect[3] = UIManager.Singleton.WorldToScreenPoint(mScreenRect[3]);
    }

    public void OnDrag(PointerEventData eventData)
    {
        check(eventData.position);
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        check(eventData.position);
    }

    private void check(Vector2 screenPos)
    {
        screenPos.x = Mathf.InverseLerp(mScreenRect[1].x, mScreenRect[2].x, screenPos.x);
        screenPos.y = Mathf.InverseLerp(mScreenRect[0].y, mScreenRect[1].y, screenPos.y);

        if (OnTouch != null)
            OnTouch(screenPos);
    }

    /// <summary>
    /// 添加事件
    /// </summary>
    /// <param name="callback"></param>
    public void addListener(Action<Vector2> callback)
    {
        OnTouch += callback;
    }

    /// <summary>
    /// 设置事件
    /// </summary>
    /// <param name="callback"></param>
    public void setListener(Action<Vector2> callback)
    {
        OnTouch = callback;
    }

    /// <summary>
    /// 移除事件
    /// </summary>
    /// <param name="callback"></param>
    public void removeListener(Action<Vector2> callback)
    {
        OnTouch -= callback;
    }

    /// <summary>
    /// 移除所有事件 
    /// </summary>
    /// <param name="button"></param>
    public void removeAllListeners()
    {
        OnTouch = null;
    }
}
